package com.lznAdmin.security.config;

import com.lznAdmin.base.lznAdminResult;
import com.lznAdmin.properties.LoginResponseType;
import com.lznAdmin.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("customAuthenticationFailHandler")
// public class CustomAuthenticationFailHandler implements AuthenticationFailureHandler {
public class CustomAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    SecurityProperties securityProperties;

    // @Override
    // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
    //                                     AuthenticationException exception) throws IOException, ServletException {
    //
    //     response.setContentType("application/json;charset=UTF-8");
    //     ServletOutputStream outputStream = response.getOutputStream();
    //
    //     lznAdminResult result = lznAdminResult.no("用户名或密码错误");
    //
    //     outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
    //
    //     outputStream.flush();
    //     outputStream.close();
    // }
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception)
            throws IOException, ServletException {

        if (LoginResponseType.JSON.equals(securityProperties.getAuthentication().getLoginType())) {
            String referer = request.getHeader("Referer");
            logger.info("Referer:" + referer);
            // Object token = new Object();
            // token = "c406628a-5ba6-49e1-9bcd-338954fd677c";

            // 认证失败响应JSON字符串
            lznAdminResult result = lznAdminResult.build(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(result.toJsonString());
            logger.info(String.valueOf(HttpStatus.UNAUTHORIZED.value()) + "---" + exception.getMessage());
        } else {
            // 重写向回认证页面，注意加上 ?error
            super.setDefaultFailureUrl(securityProperties.getAuthentication().getLoginPage() + "?error");
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}

